import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/event/LoginEvent.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/login/BindWx.dart';
import 'package:panda/login/UserLogin.dart';
import 'package:panda/set/ArticleDetail.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:wechat_kit/wechat_kit.dart';

class WelComePage extends StatefulWidget {
  int type = 0;
  WelComePage({Key key, this.type}) : super(key: key);

  @override
  _WelComePageState createState() => _WelComePageState();
}

class _WelComePageState extends State<WelComePage> {
  bool isLogin = false, isWxInstall = true, showPhone = false;
  Wechat _wechat = Wechat()
    ..registerApp(
      appId: WX_APPID,
      universalLink: WECHAT_UNIVERSAL_LINK,
    );
  StreamSubscription<WechatAuthResp> _auth;
  WechatAuthResp _authResp;
  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid)
      getString("ISAGREE").then((value) {
        if (value == null) {
          show();
        }
      });
    checkWx();
    _auth = _wechat.authResp().listen(_listenAuth);
    isLogin = (widget.type == 1);
  }

  show() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return new WillPopScope(
              onWillPop: () async => false, //重点此举
              child: AlertDialog(
                  title:
                      Text('熊猫新零售', style: TextStyle(color: Colors.blueAccent)),
                  content: Container(
                    child: Column(
                      children: <Widget>[
                        Text(
                          '谢谢您使用熊猫新零售,我们依据最新的监管要求更新了《用户协议》和《隐私政策》，特向您说明如下：\n1， 为向您提供交易相关的基本功能，我们会收集、使用必要的信息。\n2， 基于您的授权我们可能会获取您的位置等信息，您有权拒绝或取消授权。',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                        Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.of(context).push(
                                      MaterialPageRoute(builder: (context) {
                                    return new ArticleDetailPage(
                                      article_id: "2",
                                    );
                                  }));
                                },
                                child: Text(
                                  '《用户协议》',
                                  style: TextStyle(
                                      decoration: TextDecoration.none,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Color.fromARGB(255, 67, 181, 41)),
                                ),
                              ),
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.of(context).push(
                                      MaterialPageRoute(builder: (context) {
                                    return new ArticleDetailPage(
                                      article_id: "13",
                                    );
                                  }));
                                },
                                child: Text(
                                  '《隐私政策》',
                                  style: TextStyle(
                                      decoration: TextDecoration.none,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Color.fromARGB(255, 67, 181, 41)),
                                ),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                    height: DP_200,
                  ),
                  actions: <Widget>[
                    FlatButton(
                        child: Text("同意使用"),
                        onPressed: () {
                          saveString("ISAGREE", "1");
                          Navigator.of(context).pop(1);
                        }),
                    FlatButton(
                        child: Text("拒绝",
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE))),
                        onPressed: () {
                          SystemChannels.platform
                              .invokeMethod('SystemNavigator.pop');
                        })
                  ]));
        });
  }

  checkWx() async {
    // Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    // Response<String> response =
    //     await HttpUtil().post(Api.VERSION_CHECK, data: getSign(map));
    // Map userMap = json.decode(response.data);
    // if (userMap['code'] == 1 && mounted) {
    isWxInstall = await _wechat.isInstalled();
    if (!isWxInstall) {
      showPhone = false;
    } else {
      showPhone = true;
    }
    setState(() {});
    // }
  }

  void _listenAuth(WechatAuthResp resp) {
    _authResp = resp;
    if (_authResp != null &&
        _authResp.errorCode == WechatSdkResp.ERRORCODE_SUCCESS) {
      _wechat
          .getAccessTokenUnionID(
        appId: WX_APPID,
        appSecret: WX_APP_SECRET,
        code: _authResp.code,
      )
          .then((WechatAccessTokenResp accessTokenResp) {
        if (accessTokenResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
          _wechat
              .getUserInfoUnionID(
            openId: accessTokenResp.openid,
            accessToken: accessTokenResp.accessToken,
          )
              .then((WechatUserInfoResp userInfoResp) {
            if (userInfoResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) {
                    return new NetLoadingDialog(
                      loadingText: "检测中...",
                      bgColor: Color.fromARGB(255, 0, 0, 0),
                      requestCallBack: null,
                      outsideDismiss: false,
                    );
                  });
              checkIsWxBind(userInfoResp);
              // _showTips(
              //     '用户信息', '${userInfoResp.nickname} - ${userInfoResp.sex}');
            }
          });
        }
      });
    } else {
      Fluttertoast.showToast(msg: "微信登录失败");
    }
  }

  checkIsWxBind(WechatUserInfoResp resp) async {
    Map map = new Map();
    map['openid'] = resp.openid;
    map['unionid']=resp.unionid;
    map['type'] = "wx";
    map['sign_type'] = SignType.CHECK_WX_IS_BIND;
    Response<String> response =
        await HttpUtil().post(Api.CHECK_WX_IS_BIND, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    print(map);
    Navigator.of(context).pop(1);
    if (code == 1 && mounted) {
      Fluttertoast.showToast(msg: "登录成功");
      saveString(TOKEN, userMap['data']['token']);
      saveString(UID, userMap['data']['uid'].toString());
      saveString(GROUP_ID, userMap['data']['group_id'].toString());
       APPLIC.GG = 0;
      APPLIC.eventBus.fire(LoginEvent());
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: msg);
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new BindWxPage(
          type: "wx",
          openId: resp.openid,
          nickname: resp.nickname,
          avatar: resp.headimgurl,
          unionId:resp.unionid,
          sex: resp.sex.toString(),
        );
      }));
    }
  }

  @override
  void dispose() {
    if (_auth != null) {
      _auth.cancel();
    }
    super.dispose();
  }

  Future<bool> _onWillPop() {
    return Future.value(isLogin);
  }
  @override
  Widget build(BuildContext context) {
    return  new WillPopScope(
        onWillPop: Platform.isIOS?null:_onWillPop,
        child: Container(
            padding: EdgeInsets.only(
                top: ScreenUtil.getInstance().setHeight(DP_200)),
            color: white,
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                new Image.asset(
                  'images/app_icon.png',
                  fit: BoxFit.cover,
                  width: ScreenUtil.getInstance().setHeight(DP_150),
                  height: ScreenUtil.getInstance().setHeight(DP_150),
                ),
                Container(height: 10),
                Text('熊猫新零售',
                    style: TextStyle(
                        letterSpacing: 5,
                        decoration: TextDecoration.none,
                        color: Colors.black87,
                        fontSize: ScreenUtil.getInstance()
                            .setSp(BIG_FONT_SIZE + 10))),
                // Expanded(child: Center()),
                Expanded(child: Center(), flex: 2),

                Offstage(
                  offstage: !showPhone,
                  child: new Container(
                    width: double.infinity,
                    height: ScreenUtil.getInstance().setHeight(DP_80),
                    margin: EdgeInsets.only(
                        left: ScreenUtil.getInstance().setWidth(DP_150),
                        right: ScreenUtil.getInstance().setWidth(DP_150),
                        bottom: ScreenUtil.getInstance().setWidth(20)),
                    decoration: new BoxDecoration(
                        color: Color.fromARGB(255, 67, 181, 41),
                        borderRadius: BorderRadius.circular(
                            ScreenUtil.getInstance().setHeight(DP_10))),
                    padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                    child: new FlatButton(
                      child: new Padding(
                        padding: EdgeInsets.all(0.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset("images/login_wechat.png"),
                            Container(width: 5),
                            new Text(
                              "微信注册登录",
                              style: new TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE + 2)),
                            )
                          ],
                        ),
                      ),
                      onPressed: () {
                        if (!isWxInstall) {
                          Fluttertoast.showToast(msg: "请先安装微信客户端");
                          return;
                        }
                        // print('object');
                        _wechat.auth(
                          scope: <String>[WechatScope.SNSAPI_USERINFO],
                          state: 'auth',
                        );
                      },
                    ),
                  ),
                ),
                // Container(height: 15),
                Offstage(
                  offstage: showPhone,
                  child: new Container(
                    width: double.infinity,
                    height: ScreenUtil.getInstance().setHeight(DP_80),
                    margin: EdgeInsets.only(
                        left: ScreenUtil.getInstance().setWidth(DP_150),
                        right: ScreenUtil.getInstance().setWidth(DP_150),
                        bottom: ScreenUtil.getInstance().setWidth(20)),
                    decoration: new BoxDecoration(
                        border: Border.all(color: mainColor, width: 1),
                        color: mainColor,
                        borderRadius: BorderRadius.circular(
                            ScreenUtil.getInstance().setHeight(10))),
                    padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                    child: new FlatButton(
                      child: new Padding(
                        padding: EdgeInsets.all(0.0),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset("images/login_phone.png"),
                              Container(width: 8),
                              new Text(
                                "手机登录",
                                style: new TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE + 2)),
                              )
                            ]),
                      ),
                      onPressed: () {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (context) {
                          return new LoginPage();
                        }));
                      },
                    ),
                  ),
                ),
               Offstage(
                  offstage: !isWxInstall,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      showPhone = !showPhone;
                      setState(() {});
                    },
                    child: Column(children: <Widget>[
                      Text(
                        isWxInstall ? '其他方式登录' : '',
                        style: TextStyle(
                            decoration: TextDecoration.none,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black45),
                      ),
                      Icon(
                        showPhone
                            ? Icons.keyboard_arrow_down
                            : Icons.keyboard_arrow_down,
                        color: Colors.black45,
                      )
                    ]))),
                Expanded(child: Center(), flex: 1),
                Container(
                  padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setWidth(DP_80),
                      ScreenUtil.getInstance().setWidth(0),
                      ScreenUtil.getInstance().setWidth(DP_40),
                      ScreenUtil.getInstance().setWidth(DP_150)),
                  child: Row(
                    children: <Widget>[
                      Text(
                        '登录注册代表同意熊猫新零售',
                        style: TextStyle(
                            decoration: TextDecoration.none,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE - 2),
                            color: Colors.black54),
                      ),
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            return new ArticleDetailPage(
                              article_id: "2",
                            );
                          }));
                        },
                        child: Text(
                          '用户协议',
                          style: TextStyle(
                              decoration: TextDecoration.none,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE - 2),
                              color: Color.fromARGB(255, 67, 181, 41)),
                        ),
                      ),
                      Text(
                        '和',
                        style: TextStyle(
                            decoration: TextDecoration.none,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE - 2),
                            color: Colors.black54),
                      ),
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            return new ArticleDetailPage(
                              article_id: "13",
                            );
                          }));
                        },
                        child: Text(
                          '隐私政策',
                          style: TextStyle(
                              decoration: TextDecoration.none,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE - 2),
                              color: Color.fromARGB(255, 67, 181, 41)),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            )));
  }
}
